package guilddao

import (
	"context"
	"github.com/gogf/gf/v2/frame/g"
	"xr-game-server/core/cache"
	"xr-game-server/core/constants/db"
	"xr-game-server/core/lambda"
	"xr-game-server/entity"
)

var applyCache *cache.CacheMgr

func initApply() {
	applyCache = cache.NewCacheMgr()
}

// GetApply 工会长拉取申请列表
func GetApply(guildId uint64) []*entity.GuildApplication {
	cacheData := applyCache.GetData(guildId, func(ctx context.Context) (value interface{}, err error) {
		var ret []*entity.GuildApplication
		g.Model(string(entity.TbGuildApplication)).Unscoped().Where(g.Map{
			string(entity.GuildAppGuildId): guildId,
			string(db.IsDeletedName):       false,
		}).Scan(&ret)
		return ret, nil
	})
	return cacheData.([]*entity.GuildApplication)
}

// AddApply 添加工会长端申请缓存
func AddApply(data *entity.GuildApplication) {
	cacheData := GetApply(data.GuildId)
	cacheData = append([]*entity.GuildApplication{data}, cacheData...)
	applyCache.FlushCache(data.GuildId, cacheData)
}

// RemoveApply 移除工会长端申请缓存
func RemoveApply(guildId uint64, roleId uint64) {
	cacheData := GetApply(guildId)
	cacheData = lambda.Filter(cacheData, func(item *entity.GuildApplication) bool {
		if item.RoleId == roleId {
			item.SetIsDeleted(true)
		}
		return item.RoleId != roleId
	})
	applyCache.FlushCache(guildId, cacheData)
}
